﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Options;
using Nancy.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Link_eLab.Helper
{
    public static class DataHelper
    {
        #region 基本设置信息

        public static string Url = UtilConfig.DataUrl;        // 接口地址

        #endregion

        #region 请求外部接口并接收返回数据 (默认GET请求)

        /// <summary>
        /// 请求外部接口并接收返回数据 (默认GET请求)
        /// </summary>
        /// <param name="controllerName">访问的控制器名称 (示例：JwtAPI/User/UserListByBackStage)</param>
        /// <param name="param">请求地址附加的参数 (示例：id=1,name=admin)</param>
        /// <param name="method">请求类型 (GET、POST)</param>
        /// <returns>JSON结果集</returns>
        public static string HttpWebRequestData(string controllerName, string param, string method = "GET")
        {
            // 查看已设置的参数
            Console.WriteLine($"\n配置文件设置的Url：{Url}");
            Console.WriteLine($"ControllerName：{controllerName}");
            Console.WriteLine($"Param：{param}");
            Console.WriteLine($"Method：{method}");

            // 设置请求地址连接
            string requestUrl = $"{Url}{controllerName}?{param}";
            Console.WriteLine($"即将请求的地址链接：{requestUrl}");

            // 存储接口返回的数据
            string result = null;

            // Web请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = method;
            request.Accept = "application/json";
            request.ContentType = "application/json; charset=utf-8";
            request.ContentLength = 0;

            // 获取接口返回值
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // 以流的方式读取返回的数据
            Stream stream = response.GetResponseStream();

            // 获取内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            //Console.WriteLine($"\n接口返回的数据：\n{result}\n");

            return result;
        }

        #endregion

        #region 获取全部用户数据信息

        /// <summary>
        /// 获取全部用户数据信息
        /// </summary>
        /// <returns>JSON结果集</returns>
        public static List<UserModel> GetAllUserData()
        {
            string resData = HttpWebRequestData("JwtAPI/Users/UserListByBackStage", "searchParam={}", "GET");

            // 通用处理数据-json字符串转为对象
            JObject jo = JObject.Parse(resData);

            // json字符串转为对象, 反序列化
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<UserModel> udata = Serializer.Deserialize<List<UserModel>>(jo["data"].ToString());

            #region 原始方案

            //JObject jo = JObject.Parse(resData);
            //List<UserModel> udata = new List<UserModel>();
            //foreach (var item in jo["data"])
            //{
            //    udata.Add(new UserModel()
            //    {
            //        Guid = item["guid"].ToString(),
            //        OrgGuid = item["orgGuid"].ToString(),
            //        Phone = item["phone"].ToString(),
            //        Name = item["name"].ToString(),
            //        WeChatOpenId = item["weChatOpenId"].ToString(),
            //        VirtualCard = item["virtualCard"].ToString(),
            //    });
            //}

            #endregion

            Console.WriteLine($"UserDataCount：{udata.Count()}");

            return udata;
        }

        #endregion

        #region 获取当前组织的全部用户数据信息

        /// <summary>
        /// 获取当前组织的全部用户数据信息
        /// </summary>
        /// <param name="orgId">组织ID</param>
        /// <returns>JSON结果集</returns>
        public static List<UserModel> GetUserDataByOrg(string orgId)
        {
            string resData = HttpWebRequestData("JwtAPI/Users/UserListByBackStage", "searchParam={\"OrgGuid\":\"" + orgId + "\"}", "GET");

            // 通用处理数据-json字符串转为对象
            JObject jo = JObject.Parse(resData);

            // json字符串转为对象, 反序列化
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<UserModel> udata = Serializer.Deserialize<List<UserModel>>(jo["data"].ToString());

            Console.WriteLine($"UserDataCount：{udata.Count()}");

            return udata;
        }

        #endregion

        #region 将用户Guid转换为姓名

        /// <summary>
        /// 将用户Guid转换为姓名 (方案1：默认方案)
        /// </summary>
        /// <param name="udata">用户信息数据源</param>
        /// <param name="guidString">用户Guid</param>
        /// <returns>JSON结果集</returns>
        public static string ConvertGuidToName(List<UserModel> udata, string guidString)
        {
            const string nullOrEmptyPlaceholder = "无";

            // 没有时视为无
            if (string.IsNullOrEmpty(guidString))
            {
                return nullOrEmptyPlaceholder;
            }

            // 保存用户名
            var userName = new List<string>();

            // Guid字段分开，依次检查每个
            foreach (var userGuid in guidString.Split(','))
            {
                // 所有用户里找Guid相同的
                Parallel.ForEach(udata, user =>
                {
                    if (user.Guid == userGuid)
                    {
                        // 保存用户名
                        //Console.WriteLine($"Name：{user.Name}");
                        userName.Add(user.Name);
                    }
                });
            }

            // 没有时视为无
            return userName.Count > 0 ? string.Join(',', userName) : nullOrEmptyPlaceholder;
        }

        #region 将 Guid 转换为姓名 (方案2)

        /// <summary>
        /// 将 Guid 转换为姓名 (方案2)
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="id"></param>
        /// <returns>JSON结果集</returns>
        public static string ConvertUserGuidToName(List<UserModel> datas, string id)
        {
            string names = "";
            string[] ids = id.Split(",");

            for (int item = 0; item < ids.Length; item++)
            {
                var filter = from i in datas
                             where i.Guid == ids[item]
                             select i;

                if (filter.Count() > 0)
                {
                    UserModel model = filter.First();
                    names += model.Name;
                }

                if (item != ids.Length - 1)
                {
                    names += ",";
                }
            }

            return names;
        }

        #endregion

        #region 将 Guid 转换为姓名 (方案3)

        ///// <summary>
        ///// 将 Guid 转换为姓名 (方案3)
        ///// </summary>
        ///// <param name="datas"></param>
        ///// <param name="id"></param>
        ///// <returns>JSON结果集</returns>
        //public static string ConvertUserGuidToName(List<UserModel> datas, string id)
        //{
        //    var filter = from i in datas
        //                 where i.Guid == id
        //                 select i;

        //    if (filter.Any())
        //    {
        //        UserModel model = filter.First();
        //        return model.Name;
        //    }
        //    else
        //    {
        //        return "";
        //    }
        //}

        #endregion

        #endregion

        #region 将用户Guid转换为手机号

        /// <summary>
        /// 将用户Guid转换为手机号
        /// </summary>
        /// <param name="udata">用户信息数据源</param>
        /// <param name="guidString">用户Guid</param>
        /// <returns>JSON结果集</returns>
        public static string ConvertGuidToPhone(List<UserModel> udata, string guidString)
        {
            const string nullOrEmptyPlaceholder = "无";

            // 没有时视为无
            if (string.IsNullOrEmpty(guidString))
            {
                return nullOrEmptyPlaceholder;
            }

            // 保存手机号
            var userPhone = new List<string>();

            // Guid字段分开，依次检查每个
            foreach (var userGuid in guidString.Split(','))
            {
                // 所有用户里找Guid相同的
                Parallel.ForEach(udata, user =>
                {
                    if (user.Guid == userGuid)
                    {
                        // 保存手机号
                        //Console.WriteLine($"Phone：{user.Phone}");
                        userPhone.Add(user.Phone);
                    }
                });
            }

            // 没有时视为无
            return userPhone.Count > 0 ? string.Join(',', userPhone) : nullOrEmptyPlaceholder;
        }

        #endregion

        #region 将用户Guid转换为WeChatOpenID

        /// <summary>
        /// 将用户Guid转换为WeChatOpenID
        /// </summary>
        /// <param name="udata">用户信息数据源</param>
        /// <param name="guidString">用户Guid</param>
        /// <returns>JSON结果集</returns>
        public static string ConvertGuidToWeChatOpenID(List<UserModel> udata, string guidString)
        {
            const string nullOrEmptyPlaceholder = "无";

            // 没有时视为无
            if (string.IsNullOrEmpty(guidString))
            {
                return nullOrEmptyPlaceholder;
            }

            // 保存手机号
            var userPhone = new List<string>();

            // Guid字段分开，依次检查每个
            foreach (var userGuid in guidString.Split(','))
            {
                // 所有用户里找Guid相同的
                Parallel.ForEach(udata, user =>
                {
                    if (user.Guid == userGuid)
                    {
                        // 保存微信OpenID
                        //Console.WriteLine($"WeChatOpenId：{user.WeChatOpenId}");
                        userPhone.Add(user.WeChatOpenId);
                    }
                });
            }

            // 没有时视为无
            return userPhone.Count > 0 ? string.Join(',', userPhone) : nullOrEmptyPlaceholder;
        }

        #endregion

        #region UserModel

        public class UserModel
        {
            public string Guid { get; set; }
            public string OrgGuid { get; set; }
            public string PassWord { get; set; }
            public string OrgRemarks { get; set; }
            public string HeadPortraitUrl { get; set; }
            public string NickName { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Phone { get; set; }
            public string WeChatUnionId { get; set; }
            public string WeChatOpenId { get; set; }
            public string RoleId { get; set; }
            public string RoleCode { get; set; }
            public short Status { get; set; }
            public short Disabled { get; set; }
            public string VirtualCard { get; set; }
            public string CreateUser { get; set; }
            public DateTime CreateTime { get; set; }
            public string UpdateUser { get; set; }
            public DateTime UpdateTime { get; set; }
        }

        #endregion

    }
}
